import axios from 'axios'

//设置全局发送的请求数据的类型为json
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.headers.put['Content-Type'] = 'application/json';

//创建全局http请求
const $http = axios.create({
    APP_HOST
})

//设置全局请求过滤器
$http.interceptors.request.use(config => {
  return config
})

// 设置全局响应过滤器
$http.interceptors.response.use(config => {
  return config
})

function success(res, callback, errorCallback) {
  if (res.status === 200 && res.data && res.data.code === 200) {
    callback(res.data.data);
  } else {
    if (errorCallback) errorCallback(res.data);
  }
}

function get(url, params, callback, errorCallback) {
  $http.get(APP_HOST + url, {params : params})
      .then(res => {
        success(res, callback, errorCallback);
      }, res => {
          console.log(res.status);
      });
}

function post(url, body, callback, errorCallback) {
  $http.post(APP_HOST + url, body)
      .then(res => {
        success(res, callback, errorCallback);
      }, res => {
          console.log(res.status);
      });
}

function put(url, body, callback, errorCallback) {
  $http.put(APP_HOST + url, body)
      .then(res => {
        success(res, callback, errorCallback);
      }, res => {
          console.log(res.status);
      });
}

function delete_request(url, data, callback, errorCallback) {
  $http.delete(APP_HOST + url, {data: data})
       .then(res => {
          success(res, callback, errorCallback)
        })
        .catch(error => {
            console.log("delete catch", error)
        });
}

export default {
  get,
  post,
  delete_request,
  put,
}
